//
//  UIViewController+QTAdd.m
//  Pods
//
//  Created by 张俊博 on 16/8/23.
//
//

#import "UIViewController+QTAdd.h"
#import "QTCategoryMacro.h"
#import "NSObject+QTAssociate.h"

QTSYNTH_DUMMY_CLASS(UIViewController_QTAdd)

@implementation UIViewController (QTAdd)

+ (UIViewController*)currentViewController {
    UIViewController* rootViewController = self.applicationDelegate.window.rootViewController;
    return [self currentViewControllerFrom:rootViewController];
}

+ (UINavigationController*)currentNavigationViewController {
    UIViewController* currentViewController = self.currentViewController;
    return currentViewController.navigationController;
}

+ (UINavigationController *)rootNavigationViewController {
    if ([[UIApplication sharedApplication].keyWindow.rootViewController isKindOfClass:[UINavigationController class]]) {
        return (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    }
    return nil;
}

+ (UITabBarController *)tabBarController {
    if (![self rootNavigationViewController]) {
        return nil;
    }
    for (UIViewController *vc in [self rootNavigationViewController].viewControllers) {
        if ([vc isKindOfClass:[UITabBarController class]]) {
            return (UITabBarController *)vc;
        }
    }
    return nil;
}

+ (UINavigationController *)tabBarSelectedViewController {
    UITabBarController *tabVC = [self tabBarController];
    if (tabVC) {
        return tabVC.selectedViewController;
    } else {
        return nil;
    }
}

+ (BOOL)isCurrentRssChatVC
{
    return [[UIViewController currentViewController] isKindOfClass:NSClassFromString(@"QTRSSChatViewController")];
}

+ (BOOL)isCurrentTeamAssistVC
{
    return [[UIViewController currentViewController] isKindOfClass:NSClassFromString(@"QTTeamAssistViewController")];
}

+ (id<UIApplicationDelegate>)applicationDelegate {
    return [UIApplication sharedApplication].delegate;
}

// 通过递归拿到当前控制器
+ (UIViewController*)currentViewControllerFrom:(UIViewController*)viewController {
    if(viewController.presentedViewController != nil) {
        return [self currentViewControllerFrom:viewController.presentedViewController];
    } else if ([viewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController *)viewController;
        return [self currentViewControllerFrom:navigationController.viewControllers.lastObject];
    } else if([viewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController* tabBarController = (UITabBarController *)viewController;
        return [self currentViewControllerFrom:tabBarController.selectedViewController];
    } else {
        return viewController;
    }
//    if ([viewController isKindOfClass:[UINavigationController class]]) {
//        UINavigationController* navigationController = (UINavigationController *)viewController;
//        return [self currentViewControllerFrom:navigationController.viewControllers.lastObject];
//    } else if([viewController isKindOfClass:[UITabBarController class]]) {
//        UITabBarController* tabBarController = (UITabBarController *)viewController;
//        return [self currentViewControllerFrom:tabBarController.selectedViewController];
//    } else if(viewController.presentedViewController != nil) {
//        return [self currentViewControllerFrom:viewController.presentedViewController];
//    } else {
//        return viewController;
//    }
}

+ (void)popTwiceViewControllerAnimated:(BOOL)animated {
    [UIViewController popViewControllerWithTimes:2 animated:animated];
}

+ (void)popViewControllerWithTimes:(NSUInteger)times animated:(BOOL)animated {
    UIViewController *currentViewController = [UIViewController currentViewController];
    NSUInteger count = currentViewController.navigationController.viewControllers.count;
    if(currentViewController){
        if(currentViewController.navigationController) {
            if (count > times){
                [currentViewController.navigationController popToViewController:[currentViewController.navigationController.viewControllers objectAtIndex:count-1-times] animated:animated];
            }else { // 如果times大于控制器的数量
                NSAssert(0, @"确定可以pop掉那么多控制器?");
            }
        }
    }
}

+ (void)popToRootViewControllerAnimated:(BOOL)animated {
    UIViewController *currentViewController = [UIViewController currentViewController];
    NSUInteger count = currentViewController.navigationController.viewControllers.count;
    [UIViewController popViewControllerWithTimes:count-1 animated:YES];
}

+ (void)dismissTwiceViewControllerAnimated: (BOOL)flag completion: (void (^ __nullable)(void))completion {
    [self dismissViewControllerWithTimes:2 animated:YES completion:completion];
}


+ (void)dismissViewControllerWithTimes:(NSUInteger)times animated: (BOOL)flag completion: (void (^ __nullable)(void))completion {
    UIViewController *rootVC = [UIViewController currentViewController];
    
    if (rootVC.presentedViewController) {
        while (times > 0) {
            rootVC = rootVC.presentingViewController;
            times -= 1;
        }
        [rootVC dismissViewControllerAnimated:YES completion:completion];
    }else {
        NSAssert(0, @"确定能dismiss掉这么多控制器?");
    }
}


+ (void)dismissToRootViewControllerAnimated: (BOOL)flag completion: (void (^ __nullable)(void))completion {
    UIViewController *currentViewController = [UIViewController currentViewController];
    UIViewController *rootVC = currentViewController;
    while (rootVC.presentingViewController) {
        rootVC = rootVC.presentingViewController;
    }
    [rootVC dismissViewControllerAnimated:YES completion:completion];
}

- (void)showTipWithTipText:(NSString *)tips
{
    if (isNullStr(tips)) {
        return;
    }
    NSAssert([NSThread isMainThread], @"TipText needs to be accessed on the main thread.");
    
//    BOOL hasNavBar = NO;
//    if ([self isKindOfClass:[UINavigationController class]]) {
//        hasNavBar =  ![(UINavigationController *)self isNavigationBarHidden];
//    }
    BOOL hasNavBar = ![UIViewController currentNavigationViewController].navigationBarHidden;
    UILabel *floatTipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,  hasNavBar?(NavigationBar_HEIGHT+StatusBar_HEIGHT):StatusBar_HEIGHT , self.view.frame.size.width, 25)];
    floatTipLabel.alpha = 0.0;
    floatTipLabel.backgroundColor = [UIColor darkGrayColor];
    floatTipLabel.font = [UIFont systemFontOfSize : 14];
    floatTipLabel.textAlignment = NSTextAlignmentCenter;
    floatTipLabel.textColor = [UIColor whiteColor];
    floatTipLabel.text = tips;
    floatTipLabel.numberOfLines = 0;
    [floatTipLabel sizeToFit];
    CGFloat height = MAX(25, floatTipLabel.frame.size.height);
    floatTipLabel.frame = CGRectMake(0, hasNavBar?(NavigationBar_HEIGHT+StatusBar_HEIGHT):StatusBar_HEIGHT, self.view.frame.size.width, height);
    [[UIApplication sharedApplication].keyWindow addSubview:floatTipLabel];
//    [self.view.superview addSubview:floatTipLabel];
//    [[UIViewController currentNavigationViewController].view addSubview:floatTipLabel];
    
    [UIView animateWithDuration:0.5 animations:^{
        floatTipLabel.alpha = 0.9;
    }];
    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(removeTipLabel:) userInfo:floatTipLabel repeats:NO];
    
//    [NSTimer scheduledTimerWithTimeInterval:2.0 repeats:NO block:^(NSTimer * _Nonnull timer) {
//        [UIView animateWithDuration:0.5 animations:^{
//            floatTipLabel.alpha = 0.0;
//        } completion:^(BOOL finished) {
//            [floatTipLabel removeFromSuperview];
//            [timer invalidate];
//        }];
//    }];
}

- (void)removeTipLabel:(NSTimer *)sender {
    
    __block NSTimer *timer = sender;
    UILabel *floatTipLabel = (UILabel *)[sender userInfo];
    [timer invalidate];
    timer = nil;
    [UIView animateWithDuration:0.5 animations:^{
        floatTipLabel.alpha = 0.0;
    } completion:^(BOOL finished) {
        [floatTipLabel removeFromSuperview];
    }];
}

+ (void)needShowFPS:(BOOL)needShow {
    id nav = [UIViewController rootNavigationViewController];
    if (needShow) {
        QTSuppressPerformSelectorLeakWarning([nav performSelector:NSSelectorFromString(@"showFPSLable") withObject:nil]);
        ;
    } else {
        QTSuppressPerformSelectorLeakWarning([nav performSelector:NSSelectorFromString(@"hiddenFPSLable") withObject:nil]);
    }
}

- (void)setSlidingBackDisable:(BOOL)disable{
    self.as_dictionary[@"interactivePopGestureRecognizerDisable"] = @(disable);
    if (self.navigationController && [self.navigationController.visibleViewController isEqual:self]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = !disable;
    }
}
- (BOOL)getSlidingBackDisable{
    return [self.as_dictionary[@"interactivePopGestureRecognizerDisable"] boolValue];
}

@end

